<?php
namespace Api\Model\Amazon;

class ReportFileModel extends CommonModel{
    // 数据表前缀
    protected $tablePrefix      =   'api_';
    // 数据库配置
    protected $connection       =   'fbawarehouse';
    // 数据表名（不包含表前缀）
    protected $tableName        =   'report_files';

    protected $trueTableName    =   'api_report_files';


    /**
     * 参数：$reportData
     * 描述：插入数据进入表 api_report_files
     */
    public function insertReportFileData($reportFileData) {
        return $this->add($reportFileData);
    }

    /**
     * 描述：查找表 api_report_files
     */
    public function selectReportData($options = array()) {
        $reportData = $this->where($options)->select();
        return $reportData;
    }

    /**
     * @param null $file_name
     * @param null $report_id
     * @return array|bool
     * 根据报告ID或者文件名字获取报告信息
     */
    public function getReportFile ($fileName = NULL, $reportId = NULL) {
        if(empty($fileName) && empty($reportId))return false;

        $sql = 'SELECT * FROM `api_report_files` WHERE 1';
        !empty($fileName) && $sql .= ' AND `file_name` = \''. $fileName .'\'';
        !empty($reportId) && $sql .= ' AND `report_id` = '. $reportId;

        $reportFile = $this->query($sql);

        return empty($reportFile) ? array() : $reportFile[0];
    }

    /**
     * 返回某张表的所有字段
     */
    /*public static function getTableColumns ($tbl, $notInCol = array()) {
        if(empty($tbl)) return false;
        $cols = array();
        $sql = "SELECT COLUMN_NAME
            FROM information_schema.COLUMNS
            WHERE table_name = '{$tbl}' ";

        !empty($notInCol) && $sql .="AND COLUMN_NAME NOT IN('" . join("', '", $notInCol) . "')";
        $tblColumns = M($tbl, ' ', 'DB_fbawarehouse')->query($sql);
        foreach ($tblColumns as $tblColumn) {
            $cols[] = $tblColumn['COLUMN_NAME'];
        }

        return $cols;
    }*/

    public function updateAnalyzeStatus($reportFileId){
        $sql = 'UPDATE `api_report_files`
        SET `analyze_status` = 1, `analyze_time` = \'' . date('Y-m-d H:i:s') . '\'
        WHERE `id` = ' . $reportFileId;
        $this->query($sql);
    }

    public function getUnAnalyzeFile($reportId) {
        $sql = "SELECT `id`,`account_id`,`account_name`,`report_id`,`report_type_id`,`file_name`,`create_time`
                FROM `api_report_files`
                WHERE `create_time` >= '" . date('Y-m-d', strtotime(' -7 day')) . "'
                AND `analyze_status` = 0 ";

        $reportId && $sql .= " AND `report_id` = " . $reportId;

        $result = $this->query($sql);

        return !empty($result) ? $result : array();
    }
}